import { isArray, isArrayOfString, isFunction, isObject, isPromise, isString, isNumber } from '@/utils/is.js'
import Modal from '@/plugins/modal.js'

function getIdArr(data, uniqueKey = 'id') {
  let keys = []
  if (isArray(data)) {
    if (isArrayOfString(data)) {
      keys = data
    } else {
      keys = data.map((item) => item[uniqueKey])
    }
  } else if (isObject(data)) {
    keys = [data[uniqueKey] || '']
  } else if (isString(data) || isNumber(data)) {
    keys = [data]
  } else {
    keys = []
  }

  return keys
}

export const useActions = () => {
  // 通用的删除
  const deleteAction = (options = {}) => {
    let {
      api,
      selection = [], // 支持传递 [] / string[] / string / object
      uniqueKey = 'id',
      splitTag = ',',
      confirmMsg = '确认删除吗？',
      successMsg = '删除成功',
      failedMsg = '删除失败'
    } = options
    if (!isFunction(api)) {
      return Promise.reject('`api` 缺失')
    }

    let showSuccessMsg = true
    let showFailedMsg = false

    if (isProxy(selection)) {
      console.log('selection is under proxy')
      if (isArray(selection)) {
        selection = selection.map((item) => toRaw(item))
      } else {
        selection = toRaw(selection)
      }
    }
    const idList = getIdArr(selection, uniqueKey)
    console.log('selection', idList)
    if (idList.length === 0) {
      return Promise.reject('找不到唯一键')
    }
    const ids = idList.join(splitTag)

    const cbParams = {
      ids,
      keys: idList,
      selection,
      uniqueKey
    }
    if (typeof confirmMsg === 'function') {
      confirmMsg = confirmMsg(cbParams)
    }

    if (typeof successMsg === 'function') {
      successMsg = successMsg(cbParams)
    } else if (typeof successMsg === 'boolean' && successMsg === false) {
      showSuccessMsg = false
    }

    if (typeof failedMsg === 'function') {
      failedMsg = failedMsg(cbParams)
    } else if (typeof failedMsg === 'boolean' && failedMsg === false) {
      showFailedMsg = false
    }

    function success() {
      showSuccessMsg && Modal.msgSuccess(successMsg)
    }

    function failed() {
      showFailedMsg && Modal.msgError(failedMsg)
    }

    return new Promise((resolve, reject) => {
      Modal.confirm(confirmMsg).then(() => {
        const ret = api(ids)
        if (isPromise(ret)) {
          ret
            .then((subRet) => {
              resolve(subRet)
              success()
            })
            .catch((e) => {
              reject(e)
              failed(e)
            })
        } else {
          resolve(ret)
          success()
        }
      })
    })
  }

  return {
    deleteAction
  }
}
